//
//  WBStatusPictureView.swift
//  DXWeibo
//
//  Created by dx on 2017/1/15.
//  Copyright © 2017年 dx. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {
    
    var viewModel: WBStatusViewModel? {
        didSet {
            calcViewSize()
            
            // 设置配图视图的URL数据(被转发和原创)
            urls = viewModel?.picURLs
        }
    }
    
    /// 根据视图模型的配图视图大小，调整显示内容
    private func calcViewSize() {
        
        // 处理宽度
        // 1> 单图 - 根据配图视图的大小，修改 subViews[0] 的宽高
        if viewModel?.picURLs?.count == 1 {
            let viewSize = viewModel?.pictureViewSize ?? CGSize()
            
            let v = subviews[0]
            v.frame = CGRect(x: 0,
                             y: WBStatusPictureViewOutterMargin,
                             width: viewSize.width,
                             height: viewSize.height - WBStatusPictureViewOutterMargin)
        } else {
            // 2> 多图（无图），恢复 subViews[0] 的宽高，保证九宫格布局的完整
            let v = subviews[0]
            v.frame = CGRect(x: 0,
                             y: WBStatusPictureViewOutterMargin,
                             width: WBStatusPictureItemWidth,
                             height: WBStatusPictureItemWidth)
        }
   
        // 修改高度约束
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
    }
    
    /// 配图视图的数组
    private var urls: [WBStatusPicture]? {
        didSet {
            
            // 1. 隐藏所有的 imageView
            for v in subviews {
                v.isHidden = true
            }
            
            // 2. 遍历 urls 数组，顺序设置图像
            var index = 0
            for url in urls ?? [] {
                
                let iv = subviews[index] as! UIImageView
                
                // 4 张图像的处理
                if index == 1 && urls?.count == 4 {
                    index += 1
                }
                
                // 设置图像
                iv.cz_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                
                // 根据扩展名判断是否是 gif
                iv.subviews[0].isHidden = ((url.thumbnail_pic ?? "") as NSString).pathExtension.lowercased() != "gif"
                
                iv.isHidden = false
                
                index += 1
            }
        }
    }

    @IBOutlet weak internal var heightCons: NSLayoutConstraint!
    
    // 开始准备所有的控件，用xib开发建议使用该函数
    override func awakeFromNib() {
        setupUI()
    }
    
    /// @param selectedIndex    选中照片索引
    /// @param urls             浏览照片 URL 字符串数组
    /// @param parentImageViews 父视图的图像视图数组，用户展现和解除转场动画参照
    // MARK: - 监听方法
    @objc fileprivate func tapImageView(tap: UITapGestureRecognizer) {
        guard let iv = tap.view,
            let picURLs = viewModel?.picURLs
            else {
            return
        }
        
        var selectedIndex = iv.tag
        
        // 针对四张图片的处理
        if picURLs.count == 4 && selectedIndex > 1 {
            selectedIndex -= 1
        }
        
        let urls = (picURLs as NSArray).value(forKey: "largePic") as! [String]
        
        // 处理可见的图像视图数组
        var imageViewList = [UIImageView]()
        
        for iv in subviews as! [UIImageView] {
            
            if !iv.isHidden {
                imageViewList.append(iv)
            }
        }
        
        // 发送通知
        NotificationCenter.default.post(
            name: NSNotification.Name(rawValue: WBStatusCellBrowserPhotoNotification),
            object: self,
            userInfo: [WBStatusCellBrowserPhotoSelectedIndexKey: selectedIndex,
                       WBStatusCellBrowserPhotoURLsKey: urls,
                       WBStatusCellBrowserPhotoImageViewsKey: imageViewList])
    }
}

// MARK: - 设置界面
extension WBStatusPictureView {
    
    // 原则：
    // 1. cell中所有控件提前准备好
    // 2. 设置的时候，根据数据决定是否显示
    // 2. 不要动态创建控件
    fileprivate func setupUI() {
        
        // 设置背景颜色
        backgroundColor = superview?.backgroundColor
        
        // 超出边界的内容不显示
        clipsToBounds = true
        
        let count = 3
        let rect = CGRect(x: 0,
                          y: WBStatusPictureViewOutterMargin,
                          width: WBStatusPictureItemWidth,
                          height: WBStatusPictureItemWidth)
        
        for i in 0..<count * count {
            
            let iv = UIImageView()
            
            // 设置 contentMode 
            iv.contentMode = .scaleAspectFill
            iv.clipsToBounds = true
            
            let row = CGFloat(i / count)
            let col = CGFloat(i % count)
            
            let xOffset = col * (WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin)
            let yOffset = row * (WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin)
                
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
            
            self.addSubview(iv)
            
            // 能够接收用户交互
            iv.isUserInteractionEnabled = true
            
            // 添加手势识别
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapImageView))
            iv.addGestureRecognizer(tap)
            
            // 设置 tag
            iv.tag = i
            
            addGifView(iv: iv)
        }
    }
    
    private func addGifView(iv: UIImageView) {
        
        let gifImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        
        iv.addSubview(gifImageView)
        
        // 自动布局
        gifImageView.translatesAutoresizingMaskIntoConstraints = false
        
        iv.addConstraint(NSLayoutConstraint(item: gifImageView,
                                            attribute: .right,
                                            relatedBy: .equal,
                                            toItem: iv,
                                            attribute: .right,
                                            multiplier: 1.0,
                                            constant: 0))
        iv.addConstraint(NSLayoutConstraint(item: gifImageView,
                                            attribute: .bottom,
                                            relatedBy: .equal,
                                            toItem: iv,
                                            attribute: .bottom,
                                            multiplier: 1.0,
                                            constant: 0))
    }
}





















